package com.ncmmall.api.apis.mall;


import com.ncmmall.api.apis.service.Result;
import com.ncmmall.application.business.member.MemberApplication;
import com.ncmmall.domain.business.goods.Goods;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.primitives.Longs;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author linxs
 * 分类接口
 */
@RestController
@RequestMapping(value = "/channel")
@Component
public class ChannelApi {

    private Logger logger = LoggerFactory.getLogger(ChannelApi.class);

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private MemberApplication memberApplication;

    @Value("${store.domain}")
    private String storeDomain;


    /**
     * 分类
     *
     * @param params
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Result list(HttpServletRequest request) {
        Result result = new Result();
        try {

            List<Map<String, Object>> goodsChannels = queryChannelService.selectAllMap("select * from mall_goods_channel where status = 1 and parent is null and deleteStatus = 0 ", new HashedMap());

            List<Map<String, Object>> data = Lists.newArrayList();

            for (Map<String, Object> topChannel : goodsChannels) {

                List<Map<String, Object>> middens = Lists.newArrayList();
                for (Map<String, Object> middenChannel : queryChannelService.selectAllMap("select * from mall_goods_channel where status = 1 and parent = :id  and deleteStatus = 0 ", ImmutableMap.of("id", Longs.tryParse(topChannel.get("id").toString())))) {

                    List<Map<String, Object>> bottons = Lists.newArrayList();
                    for (Map<String, Object> bottonChannel : queryChannelService.selectAllMap("select * from mall_goods_channel where status = 1 and parent = :id  and deleteStatus = 0 ", ImmutableMap.of("id", Longs.tryParse(middenChannel.get("id").toString())))) {
                        if (StringUtils.isNotBlank(bottonChannel.get("icon").toString())) {
                            bottonChannel.put("icon", storeDomain + "/uploads/" + bottonChannel.get("icon").toString());
                        }

                        bottons.add(bottonChannel);
                    }
                    middenChannel.put("children", bottons);
                    middens.add(middenChannel);
                }

                topChannel.put("children", middens);

                data.add(topChannel);

            }
            return result.ok().inject(goodsChannels);

        } catch (Exception e) {

            logger.error("[商品分类获取数据异常]", e);
            return result.fail().setMsg("网络连接失败");
        }

    }


    /**
     * 分类商品列表
     *
     * @param id        分类id
     * @param orderType 排序类型
     *                  1、最新
     *                  2、价格
     *                  3、销量
     * @param orderBy   asc 顺序
     *                  desc 逆序
     * @param maxPrice  最高价格
     * @param minPrice  最低价格
     */
    @RequestMapping(value = "/goodsList", method = RequestMethod.GET)
    @ResponseBody
    public Result goodsList(long id,
                            @RequestParam(defaultValue = "0") int orderType, String orderBy,
                            @RequestParam(defaultValue = "0") double maxPrice,
                            @RequestParam(defaultValue = "0") double minPrice,
                            @RequestParam(defaultValue = "1") int pageNo,
                            @RequestParam(defaultValue = "20") int pageSize) {
        Result result = new Result();
        try {

            QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageNo).setPageSize(pageSize);

            String hql = "select g from Goods g where g.status = 3 and g.isSupplier = 1 and (g.goodsChannel.id = :cid or g.goodsChannel.parent.id = :cid or g.goodsChannel.parent.parent.id = :cid) ";
            Map<String, Object> map = new HashMap<>();
            map.put("cid", id);

            hql = builderSQL(orderType, orderBy, maxPrice, minPrice, map, hql);

            QueryPage<Goods> page = queryChannelService.findPage(hql, pageRequest.setParams(map), Goods.class);
            for (Goods goods : page.getResult()) {
                goods.setDefaultImage(storeDomain + "/uploads/" + goods.getDefaultImage());
            }

            return result.ok().inject(page);

        } catch (Exception e) {

            logger.error("[分类商品列表获取数据异常]", e);
            return result.fail().setMsg("网络连接失败");
        }

    }

    private String builderSQL(int orderType, String orderBy, double maxPrice, double minPrice, Map<String, Object> map, String hql) {

        if (maxPrice > 0) {
            hql += " and g.defaultPrice <= :maxPrice";
            map.put("maxPrice", maxPrice);
        }

        if (minPrice > 0) {
            hql += " and g.defaultPrice >= :minPrice";
            map.put("minPrice", minPrice);
        }

        if (orderType > 0 && ("ASC".equals(orderBy.toUpperCase()) || "DESC".equals(orderBy.toUpperCase()))) {
            if (orderType == 1) {
                hql += " order by createTime " + orderBy.toUpperCase();
            } else if (orderType == 2) {
                hql += " order by defaultPrice " + orderBy.toUpperCase();
            } else if (orderType == 3) {
                //todo 按销量排序
                //                    hql += " order by createTime " + orderBy.toUpperCase();
            }
        } else {
            hql += " order by createTime desc";
        }
        return hql;
    }


}
